package com.meiwenhui.sishuwujing.app;

import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.meiwenhui.sishuwujing.entities.Article;
import com.meiwenhui.sishuwujing.entities.Book;
import com.meiwenhui.sishuwujing.entities.Catalogue;
import com.meiwenhui.sishuwujing.entities.Chapter;
import com.meiwenhui.sishuwujing.entities.Favorite;
import com.meiwenhui.sishuwujing.entities.History;
import com.orm.androrm.DatabaseAdapter;
import com.orm.androrm.Model;

public class AppContext extends Application {

	public static AppContext appContext;
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;

	@Override
	public void onCreate() {
		super.onCreate();
		appContext = this;
		initDb();
	}

	/**
	 * 检测网络是否可用
	 * 
	 * @return
	 */
	public boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}

	/**
	 * 获取当前网络类型
	 * 
	 * @return 0：没有网络 1：WIFI网络 2：WAP网络 3：NET网络
	 */
	public int getNetworkType() {
		int netType = 0;
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			if (!isEmpty(extraInfo)) {
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}

	/**
	 * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
	 * 
	 * @param input
	 * @return boolean
	 */
	public static boolean isEmpty(String input) {
		if (input == null || "".equals(input))
			return true;
		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}

	private void initDb() {
		DatabaseAdapter.setDatabaseName("sishuwujing.db");
		DatabaseAdapter databaseAdapter = DatabaseAdapter.getInstance(this);
		List<Class<? extends Model>> models = new ArrayList<Class<? extends Model>>();
		models.add(Catalogue.class);
		models.add(Book.class);
		models.add(Chapter.class);
		models.add(Article.class);
		models.add(History.class);
		models.add(Favorite.class);
		databaseAdapter.setModels(models);

	}

}
